package com.chat.demo.userservice;

import com.chat.demo.userservice.DTO.message.GroupMessageDTO;
import com.chat.demo.userservice.Entity.DAO.MessageMapper;
import com.chat.demo.userservice.Entity.Entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class Message_Broadcast_Service {

    @Autowired
    private MessageMapper mapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private WebSocketSender webSocketSender;
    @Autowired
    private User_Service userService;

    public boolean sendGroupMessage(int senderId, int roomId, String content) {
        try {
            // 存储消息到数据库
            messageMapper.sendRoomMessage(senderId, roomId, content);

            // 构造 ChatMessage 对象
            GroupMessageDTO chatMessage = new GroupMessageDTO();
            chatMessage.setContent(content);
            chatMessage.setSenderId((long) senderId);
            String name = userService.getUserById((long) senderId).getUsername();
            chatMessage.setSenderName(name);
            chatMessage.setType("GROUP");
            chatMessage.setGroupId((long) roomId);
            chatMessage.setStatus("delivered");
            chatMessage.setTimestamp(java.time.OffsetDateTime.now());

            // 广播给所有订阅了 /topic/group.{roomId} 的用户
            webSocketSender.broadcastMessageToGroup(roomId, chatMessage);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public List<Message> getGroupHistory(int roomId, int page, int size) {
        int offset = (page - 1) * size;
        return mapper.getRoomMessages(roomId, size, offset);
    }

    public boolean updateMessageStatus(int messageId, String status) {
        return mapper.updateMessageStatus(messageId, status) > 0;
    }
}
